"""
数据获取模块

负责从交易所API获取K线数据
"""

import time
import asyncio
from datetime import datetime, timedelta
from typing import List, Dict, Any, Optional
from ..core import unified_logger
from ..core.exceptions import ExchangeAPIError, NetworkError


class DataFetcher:
    """数据获取器"""
    
    def __init__(self, exchange_adapter):
        """
        初始化数据获取器
        
        Args:
            exchange_adapter: 交易所适配器实例
        """
        self.exchange = exchange_adapter
        self.logger = unified_logger.get_logger('data_fetcher')
        self.rate_limit_delay = 0.1  # API调用间隔
    
    def fetch_kline_data(self, symbol: str, period: str, 
                        start_time: int, end_time: int,
                        limit: int = 1000) -> List[Dict[str, Any]]:
        """
        获取K线数据
        
        Args:
            symbol: 交易对
            period: 时间周期
            start_time: 开始时间戳
            end_time: 结束时间戳
            limit: 单次获取限制
            
        Returns:
            K线数据列表
        """
        try:
            # 直接使用新的get_kline接口，只传递limit参数
            batch_data = self.exchange.get_kline(
                symbol=symbol,
                period=period,
                limit=limit
            )
            
            if not batch_data:
                self.logger.warning(f"未获取到K线数据: {symbol}-{period}")
                return []
            
            self.logger.data_log(symbol, period, f"成功获取 {len(batch_data)} 条K线数据")
            return batch_data
            
        except Exception as e:
            self.logger.error(f"获取K线数据失败: {e}")
            raise ExchangeAPIError(f"获取K线数据失败: {e}")
    
    def _get_period_seconds(self, period: str) -> int:
        """获取时间周期对应的秒数"""
        period_map = {
            '1m': 60,
            '5m': 300,
            '15m': 900,
            '30m': 1800,
            '1h': 3600,
            '4h': 14400,
            '1d': 86400
        }
        return period_map.get(period, 60)
    
    def fetch_latest_data(self, symbol: str, period: str, 
                         count: int = 100) -> List[Dict[str, Any]]:
        """
        获取最新的K线数据
        
        Args:
            symbol: 交易对
            period: 时间周期
            count: 获取数量
            
        Returns:
            K线数据列表
        """
        try:
            # 直接使用新的get_kline接口
            return self.exchange.get_kline(symbol, period, count)
            
        except Exception as e:
            self.logger.error(f"获取最新数据失败: {e}")
            raise ExchangeAPIError(f"获取最新数据失败: {e}")